package com.cl.blog.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cl.blog.common.Const;
import com.cl.blog.entity.BCommunity;
import com.cl.blog.entity.BCommunityReview;
import com.cl.blog.entity.BTag;
import com.cl.blog.entity.BUser;
import com.cl.blog.mapper.BCommunityReviewMapper;
import com.cl.blog.service.*;
import com.cl.blog.mapper.BCommunityMapper;
import com.cl.blog.util.JwtUtil;
import com.cl.blog.vo.CommunityAddVo;
import com.cl.blog.vo.CommunitySearchVo;
import com.github.houbb.sensitive.word.core.SensitiveWordHelper;
import io.jsonwebtoken.Claims;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import static com.cl.blog.config.RabbitMqConfig.JAVABOY_EXCHANGE_NAME;
import static com.cl.blog.config.RabbitMqConfig.JAVABOY_ROUTING_KEY;

/**
 * @author object
 * @description 针对表【b_community】的数据库操作Service实现
 * @createDate 2024-03-14 17:13:59
 */
@Service
public class BCommunityServiceImpl extends ServiceImpl<BCommunityMapper, BCommunity>
		implements BCommunityService {

	@Autowired
	BUserService bUserService;
	@Autowired
	BCommunityExamineService bCommunityExamineService;
	@Autowired
	JwtUtil jwtUtil;
	@Autowired
	RabbitTemplate rabbitTemplate;
	@Autowired
	BCommunityReviewMapper bCommunityReviewMapper;
	@Autowired
	BCommunityReviewService bCommunityReviewService;
	@Autowired
	BTagService bTagService;
	@Autowired
	BCommunityMapper bCommunityMapper;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean addCommunity(CommunityAddVo form, String token) {
		// 获取用户信息
		Claims claim = jwtUtil.getClaimByToken(token, Const.GRADE_USER);
		String userId = claim.getSubject();

		boolean contains = SensitiveWordHelper.contains(form.getContent());
		String newContent = null;
		if (contains) {
			// 包含敏感词
			newContent = SensitiveWordHelper.replace(form.getContent());
		} else {
			newContent = form.getContent();
		}
		String result = form.getTags().stream()
				.map(Object::toString)
				.collect(Collectors.joining(","));

		System.out.println("上传的评论-->" + newContent + "---" + form.getContent());

		// 添加评论
		BCommunity bCommunity = new BCommunity();
		bCommunity.setContent(newContent);
		bCommunity.setUserId(Integer.valueOf(userId));
		bCommunity.setStatus(0);
		bCommunity.setCreateTime(LocalDateTime.now());
		bCommunity.setLikeCount(0L);
		bCommunity.setReviewCount(0L);
		bCommunity.setCommunityId(IdUtil.fastSimpleUUID());
		bCommunity.setTagsId(result);
		bCommunity.setLook(0L);
		this.save(bCommunity);
		if (!contains) {
			rabbitTemplate.convertAndSend(JAVABOY_EXCHANGE_NAME, JAVABOY_ROUTING_KEY, bCommunity.getCommunityId());
		}


		return false;
	}

	@Override
	public List<BCommunity> selectAll(Integer type) {
		String orderBy = "like_count";
		List<BCommunity> list = new ArrayList<>();

		if (type == 2) {
			// 最新
			orderBy = "create_time";
			list = this.list(new QueryWrapper<BCommunity>().eq("status", 1).orderByDesc(orderBy));
		} else if (type == 3) {
			// 未解答
			list = this.list(new QueryWrapper<BCommunity>()
					.eq("status", 1)
					.eq("review_count", 0)
					.orderByDesc("create_time"));
		} else {
			list = this.list(new QueryWrapper<BCommunity>().eq("status", 1).orderByDesc(orderBy));
		}

		for (BCommunity bCommunity : list) {
			// 评论数量
			long count = bCommunityReviewService.count();
			bCommunity.setReviewCount(count);
			// 获取点赞最高的那个评论
			List<BCommunityReview> like = bCommunityReviewService.list(new QueryWrapper<BCommunityReview>()
					.orderByDesc("like_count")
					.last("limit 1")
			);
			if (like.size() > 0) {
				BUser bUser = bUserService.getById(like.get(0).getUserId());
				bCommunity.setReview(like.get(0));
				bCommunity.setBUser(bUser);
			}
			if (bCommunity.getTagsId() != null) {
				String[] split = bCommunity.getTagsId().split(",");
				List<Integer> tagsId = Arrays.stream(split).map(Integer::valueOf).collect(Collectors.toList());
				List<BTag> tags = bTagService.list(new QueryWrapper<BTag>().in("id", tagsId));
				bCommunity.setTagList(tags);
			}

		}

		return list;
	}

	@Override
	public List<BCommunity> search(CommunitySearchVo searchVo) {
		// 一周内，全部或未解答
		List<BCommunity> week = bCommunityMapper.selectByWeek(searchVo);
		for (BCommunity bCommunity : week) {
			// 评论数量
			long count = bCommunityReviewService.count();
			bCommunity.setReviewCount(count);
			// 获取点赞最高的那个评论
			List<BCommunityReview> like = bCommunityReviewService.list(new QueryWrapper<BCommunityReview>()
					.orderByDesc("like_count")
					.last("limit 1")
			);
			if (like.size() > 0) {
				BUser bUser = bUserService.getById(like.get(0).getUserId());
				bCommunity.setReview(like.get(0));
				bCommunity.setBUser(bUser);
			}
			if (bCommunity.getTagsId() != null) {
				String[] split = bCommunity.getTagsId().split(",");
				List<Integer> tagsId = Arrays.stream(split).map(Integer::valueOf).collect(Collectors.toList());
				List<BTag> tags = bTagService.list(new QueryWrapper<BTag>().in("id", tagsId));
				bCommunity.setTagList(tags);
			}

		}

		return week;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public BCommunity selectById(Integer id) {
		BCommunity bCommunity = this.getById(id);
		BUser byId = bUserService.getById(bCommunity.getUserId());
		bCommunity.setBUser(byId);

		List<BCommunityReview> reviewList = bCommunityReviewService.list(new QueryWrapper<BCommunityReview>()
				.eq("community_id", bCommunity.getId())
				.isNull("parent_id")
		);
		for (BCommunityReview bCommunityReview : reviewList) {

//			List<BCommunityReview> child = bCommunityReviewService.list(new QueryWrapper<BCommunityReview>().eq("parent_id", bCommunityReview.getId()));
			List<BCommunityReview> child = bCommunityReviewMapper.selectAllChild(bCommunityReview.getId());
			BUser bUser = bUserService.getById(bCommunityReview.getUserId());
			for (BCommunityReview communityReview : child) {
				BUser byId1 = bUserService.getById(communityReview.getUserId());
				communityReview.setUser(byId1);
			}
			bCommunityReview.setUser(bUser);
			if (child.size() > 0) {
				bCommunityReview.setChildCommunity(child);
			}

		}
		bCommunity.setLook(bCommunity.getLook() + 1);
		this.update(bCommunity, new UpdateWrapper<BCommunity>().eq("id", bCommunity.getId()));
		bCommunity.setReviewList(reviewList);
		return bCommunity;
	}


}




